<template>
	<el-drawer v-model="isShowDrawer" direction="rtl" :before-close="handleClose" :size="curDrawerSize" :close-on-click-modal="isReadOnly">
		<template #header="{ titleId, titleClass }">
			<div class="zs-drawer-header" :id="titleId" :class="titleClass">
				<i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
				<div class="zs-title zs-text-black">保养标准</div>
			</div>
		</template>

		<template #default>
			<el-container class="zs-drawer-container">
				<el-scrollbar class="zs-drawer-content">
					<!-- card1 -->
					<div class="zs-align-center zs-space-bottom" id="sm-drawer-demo-card-01">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">保养标准</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form1" label-position="right" label-width="100px" :rules="rules.rules1" :model="formData.data">
							<el-form-item label="保养标准：" prop="standard">
								<el-input v-model="formData.data.standard" :maxlength="curTextareaLength" show-word-limit type="textarea" :autosize="{ minRows: 2 }" :disabled="isReadOnly" />
							</el-form-item>
						</el-form>
					</div>
					<!-- card2 -->
					<div class="zs-align-center zs-space-top-lg zs-space-bottom" id="sm-drawer-demo-card-02">
						<i class="icon-s-item zs-icon zs-text-blue zs-space-right-sm"></i>
						<div class="zs-title">扣罚标准</div>
					</div>
					<div class="zs-card zs-space-bottom">
						<el-form ref="form2" label-position="right" label-width="100px" :rules="rules.rules2" :model="formData.data">
							<el-form-item label="单位：" prop="unit">
								<el-select class="zs-full-item" v-model="formData.data.unit" clearable :disabled="isReadOnly" @change="getUnit">
									<el-option v-for="item in dictObj.YS_WHOLE_UNIT" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
								</el-select>
							</el-form-item>
							<el-form-item label="含税单价：" prop="standardCost">
								<el-input class="zs-input-group-md" v-model="formData.data.standardCost" :disabled="isReadOnly" :class="{ 'zs-input-group-white': !isReadOnly }">
									<template #append>
										<div>{{ curUnit }}</div>
									</template>
								</el-input>
							</el-form-item>
							<el-form-item label="说明：">
								<el-input v-model="formData.data.remark" :maxlength="curTextareaLength" show-word-limit type="textarea" :autosize="{ minRows: 2 }" :disabled="isReadOnly" />
							</el-form-item>
						</el-form>
					</div>
					<!-- card3 -->
					<EffectAndFailureTime ref="effectTimeRef" title="生效状态" id="sm-drawer-demo-card-03" :isReadOnly="isReadOnly" labelWidth="110px" />
					<!-- card4 -->
					<CreateUserInfo v-if="formData.data.id" ref="createDataRef" title="创建信息" id="sm-drawer-demo-card-04" />
				</el-scrollbar>
				<hsDocWrapper :nodeList="curNodeList" />
			</el-container>
		</template>

		<template v-if="handleType != 'info'" #footer>
			<div>
				<el-button class="zs-btn-md zs-btn-primary" @click="doConfirm">提交</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
	import EffectAndFailureTime from '@/components/effectAndFailureTime.vue';
	import CreateUserInfo from '@/components/createUserInfo.vue';
	import { standardAddApi, standardUpdateApi, standardInfoApi } from '@/api/facility.js';
	import { ElMessage } from 'element-plus';
	import { ref, reactive, watch, nextTick } from 'vue';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';

	const route = useRoute();

	const props = defineProps({
		isShow: { type: Boolean, default: false },
		isReadOnly: { type: Boolean, default: true },
		handleType: { type: String, default: '' },
		currentRow: { type: Object },
	});

	let store = useStore();
	const curDrawerSize = ref(store.state.uiDrawerSize);
	const curTextareaLength = ref(store.state.uiTextareaLength);

	let dictObj = store.getters.getDictObj(['VALIDATE_FLAG', 'APPROVAL_STATUS', 'YS_WHOLE_UNIT']);

	const emit = defineEmits(['close']);

	let isShowDrawer = ref(props.isShow);

	let formData = reactive({ data: {} });

	const rules = reactive({
		rules1: {
			standard: [{ required: true, message: '请填写保养标准', trigger: ['blur', 'change'] }],
		},
		rules2: {
			unit: [{ required: true, message: '请选择单位', trigger: 'change' }],
			standardCost: [
				{ required: true, message: '请输入含税单价', trigger: 'blur' },
				{ validator: twoDecimalPlaces('taxPrice'), trigger: ['change', 'blur'] },
			],
		},
	});

	const curNodeList = ref([
		{ name: '保养标准', id: 'sm-drawer-demo-card-01' },
		{ name: '扣罚标准', id: 'sm-drawer-demo-card-02' },
		{ name: '生效状态', id: 'sm-drawer-demo-card-03' },
	]);

	const form1 = ref();
	const form2 = ref();
	const forms = [form1, form2];
	const effectTimeRef = ref();
	const createDataRef = ref();

	let curUnit = ref('暂无');
	let YS_WHOLE_UNIT_OBJ = {};
	dictObj.YS_WHOLE_UNIT.forEach(el => {
		YS_WHOLE_UNIT_OBJ[el.dictValue] = el;
	});

	//含税单位
	const getUnit = val => {
		curUnit.value = YS_WHOLE_UNIT_OBJ[val]?.dictLabel || '暂无';
	};

	watch(
		() => props.isShow,
		(newVal, oldVal) => {
			isShowDrawer.value = newVal;
			nextTick(() => {
				newVal && props.handleType == 'add' && initForm();
				newVal && ['info', 'edit'].includes(props.handleType) && getInfo(props.currentRow?.id);
			});
		},
	);

	//详情
	const getInfo = async id => {
		let res = await standardInfoApi(id);
		if (res.data.code !== 200) return;
		let existCreate = curNodeList.value.find(item => item.id === 'sm-drawer-demo-card-04');
		!existCreate && curNodeList.value.push({ name: '创建信息', id: 'sm-drawer-demo-card-04' });
		formData.data = Object.assign(res.data.data);
		getUnit(formData.data.unit);
		effectTimeRef.value.setTime({ effectTime: formData.data.startTime, expireTime: formData.data.endTime });
		nextTick(() => {
			createDataRef.value.setData(formData.data);
		});
	};

	//提交
	const doConfirm = async () => {
		const validatePromises = forms.map(form => new Promise(resolve => form.value.validate(resolve)));
		const timeModel = effectTimeRef.value.checkRequired();
		validatePromises.push(timeModel)

		Promise.all(validatePromises).then(async results => {
			const isValid = results.every(valid => valid);
			if (!isValid) return;
			let params = Object.assign(formData.data, effectTimeRef.value.getFiled());
			params.facilityId = route.query.eid;
			let res = formData.data.id ? await standardUpdateApi(params) : await standardAddApi(params);
			if (res.data.code == 200) {
				ElMessage({
					message: '提交成功',
					type: 'success',
				});
				isShowDrawer.value = false;
				emit('close', { isShow: false, isRefresh: true });
			}
		});
	};

	//关闭抽屉
	const handleClose = done => {
		effectTimeRef.value.restTime();
		emit('close', { isShow: false });
		done();
	};

	// 校验小数
	function twoDecimalPlaces() {
		return (rule, value, callback) => {
			if (value == 0) {
				callback();
				return;
			}
			let reg = /^(([1-9][0-9]{0,11})|(([0]\.\d{1,4}|[1-9][0-9]{0,8}\.\d{1,2})))$/;
			if (reg.test(value) && value > 0) {
				callback();
			} else {
				callback(new Error('纯数字,支持小数点后两位'));
			}
		};
	}

	//表单初始化
	const initForm = () => {
		formData.data = {};

		effectTimeRef.value.setTime({});

		let existCreate = curNodeList.value.find(item => item.id === 'sm-drawer-demo-card-04');
		existCreate && curNodeList.value.pop();

		forms.forEach(form => {
			form.value.resetFields();
		});
	};

	defineExpose({ initForm, getInfo });
</script>
